package com.roadjava.rbac.security.handler;

import com.roadjava.rbac.bean.dto.SecurityUserDTO;
import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.manager.CacheManager;
import com.roadjava.rbac.util.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhaodaowen
 *
 */
@Component
public class LogoutHandlerImpl implements LogoutHandler {
    @Resource
    private CacheManager cacheManager;
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            // 清空redis中的用户信息
            cacheManager.delete(dto.getUsername());
            // 清空security 上下文 filterChain,在SecurityContextPersistenceFilter中已清空
            // 返回给前端信息
            Result<String> result = Result.buildSuccess("注销成功");
            ResponseUtil.respAppJson(response,result);
        }
    }
}
